<script setup lang="ts">
import type { FavoriteVO } from '#/api/company/favorite/model';

import { h } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import {
  favoriteDistinct,
  favoriteFindRepeatCount,
} from '#/api/company/favorite';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { distinctDrawerSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-2',
    // 默认label宽度 px
    labelWidth: 120,
    // 通用配置项 会影响到所有表单项
    componentProps: {
      class: 'w-full',
    },
    colon: true,
  },
  schema: distinctDrawerSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicDrawer, drawerApi] = useVbenDrawer({
  // 在这里更改宽度
  class: 'w-[700px]',
  confirmText: '确认去重',
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    drawerApi.drawerLoading(true);

    const { favorites } = drawerApi.getData();

    const repeatCount = await favoriteFindRepeatCount(
      favorites.map((v: FavoriteVO) => v.id),
    );

    formApi.updateSchema([
      {
        componentProps: {
          tagList: favorites.map((v: FavoriteVO) => {
            return { label: v.name, value: v.id };
          }),
        },
        fieldName: 'favoriteIds',
      },
      {
        componentProps: {
          favorites,
        },
        fieldName: 'retainFavoriteId',
      },
      {
        component: h('span', { class: 'text-sm' }, repeatCount),
        fieldName: 'repeatCount',
      },
    ]);

    await markInitialized();

    drawerApi.drawerLoading(false);
  },
});

async function handleConfirm() {
  try {
    drawerApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    // getValues获取为一个readonly的对象 需要修改必须先深拷贝一次
    const data = cloneDeep(await formApi.getValues());
    await favoriteDistinct(data);
    console.log(data);
    resetInitialized();
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    drawerApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicDrawer title="公司收藏夹去重">
    <BasicForm />
  </BasicDrawer>
</template>
